<?php
class ome_ctl_admin_consign extends desktop_controller{
    var $name = "发货处理";
    var $workground = "delivery_center";

    function index(){
        $consign = &app::get('ome')->getConf('ome.delivery.consign');
        $deliveryObj  = &$this->app->model('delivery');
        $this->pagedata['num'] = $deliveryObj->countNoProcessDelivery();
        if ($consign == 'single')
            $this->page("admin/delivery/process_consign_index.html");
        else
            $this->page("admin/delivery/process_consign_batch.html");
    }

    function batchCheck(){
        $ids = urldecode($_POST['delivery_id']);
        $weight = $_POST['weight'];
        if (empty($ids)){
            $tmp = array(array('bn'=>'*','msg'=>'请扫描快递单号'));
            echo json_encode($tmp);die;
        }

        //逐个发货：发货判断，批量发货不做此过滤
        if ($_GET['delivery_type'] == 'single'){
            $return_error = $this->consign_filter('', $ids, $weight);
            if ($return_error){
                $tmp = array('status'=>'error','msg'=>$return_error);
                echo json_encode($tmp);die;
            }
        }

        $oBranch = &app::get('ome')->model('branch');
        $is_super = kernel::single('desktop_user')->is_super();
        $branch_ids = $oBranch->getBranchByUser(true);

        $delivery_list = array();
        $delivery_ids = explode(',', $ids);
        $dlyObj = &$this->app->model('delivery');

        if ($delivery_ids){
            foreach ($delivery_ids as $v){
                if (empty($v)) continue;

                $dly = $dlyObj->dump(array('logi_no|nequal' => $v),'*',array('delivery_items'=>array('*')));
                $delivery_list[] = $dly['delivery_id'];
                if (!$dly){
                    $tmp[] = array('bn'=>$v,'msg'=>'无此快递单号');
                    continue;
                }
                if (!$is_super){
                   if (!in_array($dly['branch_id'],$branch_ids)){
                       $tmp[] = array('bn'=>$v,'msg'=>'你无权对此快递单进行发货');
                       continue;
                   }
                }

                if (!$dlyObj->existOrderStatus($dly['delivery_id'], $dly['is_bind'])){
                    $tmp[] = array('bn'=>$v,'msg'=>'此快递单号对应发货单不处于可发货状态');
                    continue;
                }
                if (!$dlyObj->existOrderPause($dly['delivery_id'], $dly['is_bind'])){
                    $tmp[] = array('bn'=>$v,'msg'=>'对应发货单订单已暂停');
                    continue;
                }
                if ($dly['status'] == 'back'){
                    $tmp[] = array('bn'=>$v,'msg'=>'对应发货单已打回');
                    continue;
                }
                if ($dly['verify'] == 'false'){
                    $tmp[] = array('bn'=>$v,'msg'=>'对应发货单未校验');
                    continue;
                }
                if ($dly['process'] == 'true'){
                    $tmp[] = array('bn'=>$v,'msg'=>'对应发货单已发货');
                    continue;
                }
                foreach ($dly['delivery_items'] as $item){
                    if ($item['verify'] == 'false'){
                        $tmp[] = array('bn'=>$v,'msg'=>'对应发货单已发货');
                        break;
                    }
                    $re = $dlyObj->existStockIsPlus($item['product_id'],$item['number'],$item['item_id'],$dly['branch_id'],$err,$item['bn']);
                    if (!$re){
                        $tmp[] = array('bn'=>$v,'msg'=>$err);
                        break;
                    }
                }
                $orderInfo = $dlyObj->getOrderByDeliveryId($dly['delivery_id']);
                if($orderInfo['pay_status'] == '5'){
                    $tmp[] = array('bn'=>$v,'msg'=>'对应订单 '.$orderInfo['order_bn'].' 已退款');
                    continue;
                }
            }
            //获取申请过退款或已退款的订单号
            if (empty($tmp)){
                $order_exists_refund = ome_order_func::get_refund_orders($delivery_list, true);
                if ($order_exists_refund){
                    $tmp[]['order_exists_refund'] = json_encode($order_exists_refund);
                }
            }
        }
        if ($tmp){
            echo json_encode($tmp);die;
        }
        echo "";
    }

    /**
     * 批量发货确认
     * 显示批量发货订单中有退款申请或已退款的订单，让管理员确认是否发货或不发货
     * @param json $data
     * @return null
     */
    function batch_delivery_confirm($data=null){
        $this->pagedata['delivery_type'] = $_GET['delivery_type'];
        $this->display('admin/order/batch_delivery_confirm.html');
    }
    
    function batchConsign(){

        $goto_url = 'index.php?app=ome&ctl=admin_consign';
        $ids = $_POST['delivery_id'];
        $dlyObj = &$this->app->model('delivery');

        $delivery_ids = explode(',', $ids);
        
        $checkInfo = $this->checkDeliveryStatus($delivery_ids);
        if(! empty($checkInfo)) {
            $info = '';
            foreach ($checkInfo as $v) {
                $info .= $v['bn'] . ': ' . $v['msg'];
            }
            
            $this->splash('error', $goto_url, $info,'', array('msg'=>$info));
            exit;
        }

        $delivery_result = true;
        $delivery_fail_bns = array();
        $delivery_succ = 'fail';
        if ($delivery_ids)
        foreach ($delivery_ids as $id){
            if (empty($id)) continue;
            $dly = $dlyObj->dump(array('logi_no|nequal'=>$id),'delivery_bn,logi_no,delivery_id,process');
            kernel::database()->exec('begin');
            if ($dly && $dly['process']=='false'){
                if ( !$dlyObj->consignDelivery($dly['delivery_id'], 0, $msg) ){
                    $delivery_result = false;
                    $delivery_fail_bns[] = '物流单号:'.$dly['logi_no'].'-发货单号:'.$dly['delivery_bn'];
                    kernel::database()->exec('rollback');
                }else{
                    kernel::database()->exec('commit');
                    $delivery_succ = 'succ';
                }
            }else{
                $delivery_result = false;
            }
        }
        
        if ($delivery_result){
            $this->splash('success',$goto_url ,'发货完成');
            exit;
        }else{
            $msg['delivery_bn'] = implode("<br/>",$delivery_fail_bns);
            $msg['delivery_succ'] = $delivery_succ;
            if ($delivery_succ == 'succ'){
                $error_msg = '部分发货单发货失败';
            }else{
                $error_msg = '发货失败';
            }
            $this->splash('error', $goto_url, $error_msg,'', array('msg'=>$msg));
            exit;
        }
    }

    /**
     * 发货判断
     * @param array $dly 发货单dump标准结构数据
     * @param string $logi_no 物流单号
     * @param number $weight 重量
     */
    function consign_filter($dly,$logi_no,$weight='0'){
        if (empty($logi_no)){
            return '请输入快递单号';
        }
        if (empty($weight)){
            return '请输入重量信息';
        }

        $dlyObj = &$this->app->model('delivery');
        if (empty($dly)){
            $dly = $dlyObj->dump(array('logi_no|nequal' => $logi_no),'*',array('delivery_items'=>array('*'),'delivery_order'=>array('*')));
        }

        if (!$dly){
            return '无此物流运单号';
        }
        /*
         * 获取操作员管辖仓库
         */
        $oBranch = &app::get('ome')->model('branch');
        $is_super = kernel::single('desktop_user')->is_super();
        if (!$is_super){
           $branch_ids = $oBranch->getBranchByUser(true);
           if (!in_array($dly['branch_id'],$branch_ids))
               return '快递单号不在您管辖的仓库范围内';
        }

        //判断发货单相应订单是否有问题
        if (!$this->checkOrderStatus($dly['delivery_id'], true, $msg)){
            return $msg;
        }
        if ($dly['verify'] == 'false'){
            return '此物流运单号对应的发货单未校验';
        }
        if ($dly['process'] == 'true'){
            return '此物流运单号对应的发货单已发货';
        }
        foreach ($dly['delivery_items'] as $item){
            if ($item['verify'] == 'false'){
                return '此物流运单号对应的发货单详情未校验完成';
            }
            $re = $dlyObj->existStockIsPlus($item['product_id'],$item['number'],$item['item_id'],$dly['branch_id'],$err,$item['bn']);
            if (!$re){
                return $err;
            }
        }
    }

    /**
     * 发货处理
     *
     */
    function consign(){
        $this->begin("index.php?app=ome&ctl=admin_consign");

        $logi_no = $_POST['logi_no'];
        $weight  = $_POST['weight'];

        $dlyObj = &$this->app->model('delivery');
        $dly = $dlyObj->dump(array('logi_no|nequal' => $logi_no),'*',array('delivery_items'=>array('*'),'delivery_order'=>array('*')));
        $return_error = $this->consign_filter($dly, $logi_no, $weight);
        if ($return_error){
            $this->end(false, app::get('base')->_($return_error));
        }

        $oObj = $this->app->model('orders');
        
        foreach($dly['delivery_order'] as $order_id ){
            $orders = $order_id['order_id'];
            $order_detial = $oObj->dump(array('order_id'=>$orders),'pay_status');
            if($order_detial['pay_status'] == 4){
                $this->end('false','对应订单已部分退款，无法发货');
            }
            if($order_detial['pay_status'] == 5){
               $this->end('false','对应订单已全额退款，无法发货');
            }
        }

        //处理发货
        if ($dlyObj->consignDelivery($dly['delivery_id'], $weight, $msg)){
            $this->end(true, '发货处理完成');
        }else {
            $msg['delivery_bn'] = $dly['delivery_bn'];
            $this->end(false, '发货未完成', '', array('msg'=>$msg));
        }
    }

    /**
     * 判断发货单号相关订单处理状态是否处于取消或异常
     *
     * @param bigint $dly_id
     * @param String $msg 返回消息提示
     * @param boolean $msg_flag 默认false终止并提示,true不终止返回消息
     * @return null
     */
    function checkOrderStatus($dly_id, $msg_flag=false, &$msg){
        if (!$dly_id) return false;
        $Objdly = &$this->app->model('delivery');
        $delivery = $Objdly->dump($dly_id);
        if (!$Objdly->existOrderStatus($dly_id, $delivery['is_bind'])){
            $msg = "发货单已无法操作，请到订单处理中心处理";
            if ($msg_flag == false){
                echo $msg;
                exit("<script>parent.MessageBox.error('发货单已无法操作，请到订单处理中心处理!');</script>");
            }else{
                return false;
            }
        }
        if (!$Objdly->existOrderPause($dly_id, $delivery['is_bind'])){
            $msg = "发货单相关订单已暂停，请到订单处理中心处理";
            if ($msg_flag == false){
                echo $msg;
                exit("<script>parent.MessageBox.error('发货单相关订单已暂停，请到订单处理中心处理!');</script>");
            }else{
                return false;
            }
        }
        return true;
    }

    private function checkDeliveryStatus($delivery_ids) {
        $dlyObj = &$this->app->model('delivery');
		$oBranch = &app::get('ome')->model('branch');
        $is_super = kernel::single('desktop_user')->is_super();
        $branch_ids = $oBranch->getBranchByUser(true);
        
        if ($delivery_ids && is_array($delivery_ids)){
            foreach ($delivery_ids as $v){
                if (empty($v)) continue;

                $dly = $dlyObj->dump(array('logi_no|nequal' => $v),'*',array('delivery_items'=>array('*')));
                $delivery_list[] = $dly['delivery_id'];
                if (!$dly){
                    $tmp[] = array('bn'=>$v,'msg'=>'无此快递单号');
                    continue;
                }
                if (!$is_super){
                   if (!in_array($dly['branch_id'],$branch_ids)){
                       $tmp[] = array('bn'=>$v,'msg'=>'你无权对此快递单进行发货');
                       continue;
                   }
                }

                if (!$dlyObj->existOrderStatus($dly['delivery_id'], $dly['is_bind'])){
                    $tmp[] = array('bn'=>$v,'msg'=>'此快递单号对应发货单不处于可发货状态');
                    continue;
                }
                if (!$dlyObj->existOrderPause($dly['delivery_id'], $dly['is_bind'])){
                    $tmp[] = array('bn'=>$v,'msg'=>'对应发货单订单已暂停');
                    continue;
                }
                if ($dly['status'] == 'back'){
                    $tmp[] = array('bn'=>$v,'msg'=>'对应发货单已打回');
                    continue;
                }
                if ($dly['verify'] == 'false'){
                    $tmp[] = array('bn'=>$v,'msg'=>'对应发货单未校验');
                    continue;
                }
                if ($dly['process'] == 'true'){
                    $tmp[] = array('bn'=>$v,'msg'=>'对应发货单已发货');
                    continue;
                }
                foreach ($dly['delivery_items'] as $item){
                    if ($item['verify'] == 'false'){
                        $tmp[] = array('bn'=>$v,'msg'=>'对应发货单已发货');
                        break;
                    }
                    $re = $dlyObj->existStockIsPlus($item['product_id'],$item['number'],$item['item_id'],$dly['branch_id'],$err,$item['bn']);
                    if (!$re){
                        $tmp[] = array('bn'=>$v,'msg'=>$err);
                        break;
                    }
                }
                $orderInfo = $dlyObj->getOrderByDeliveryId($dly['delivery_id']);
                if($orderInfo['pay_status'] == '5'){
                    $tmp[] = array('bn'=>$v,'msg'=>'对应订单 '.$orderInfo['order_bn'].' 已退款');
                    continue;
                }
            }
            //获取申请过退款或已退款的订单号
            /*if (empty($tmp)){
                $order_exists_refund = ome_order_func::get_refund_orders($delivery_list, true);
                if ($order_exists_refund){
                    $tmp[]['order_exists_refund'] = json_encode($order_exists_refund);
                }
            }此处已经不需要判断*/
        }
        
        return $tmp;
    }
}
?>
